﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Collections.Generic
{    
    public static class GenericDictionaryExtension
    {
        public static void AddRange<TKey, TValue>(this IDictionary<TKey, TValue> dict, IEnumerable<KeyValuePair<TKey, TValue>> coll)
        {
            if (dict != null && coll != null)
                foreach (var item in coll)
                    dict.Add(item.Key, item.Value);
        }
        public static TValue GetOrCreate<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key)
            where TValue : new()
        {
            TValue res = default(TValue);
            if (!dict.TryGetValue(key, out res))
                dict.Add(key, res = new TValue());
            return res;
        }
        public static TValue GetOrAddDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defal)
        {
            TValue res = defal;
            if (!dict.TryGetValue(key, out res))
                dict.Add(key, res = defal);
            return res;
        }
        public static TValue GetOrAddDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TValue> getValueFunc)
        {
            TValue res = default(TValue); ;
            if (!dict.TryGetValue(key, out res) && getValueFunc != null)
                dict.Add(key, res = getValueFunc());
            return res;
        }
        public static TValue GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defal)
        {
            TValue res = default(TValue);
            if (!dict.TryGetValue(key, out res))
                res = defal;
            return res;
        }

		public static TValue GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TValue> getValueFunc)
		{
			TValue res = default(TValue);
			if (!dict.TryGetValue(key, out res) && getValueFunc != null)
				res = getValueFunc();
			return res;
		}

        public static TValue GetOrAddDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key)
        {
            TValue res = default(TValue);
            if (!dict.TryGetValue(key, out res))
                dict.Add(key, res);
            return res;
        }
    }
}
